package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.AddressDao;
import com.rk.kbk.dao.ServeRateDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Address;
import com.rk.kbk.model.AreaDetail;
import com.rk.kbk.model.ServeRate;
import com.rk.kbk.model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.math.BigInteger;
import java.util.List;

/**
 * @ServeRateController
 * @Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/serveRate")
public class ServeRateController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private ServeRateDao serveRateDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AddressDao addressDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加/修改
     * @param serveRate
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateServeRate",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateServeRate(@RequestBody ServeRate serveRate){
        log.debug("添加/修改");
        serveRateDao.save(serveRate);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改
     * @param serveRates
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeServeRate",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeServeRate(@RequestBody List<ServeRate> serveRates){
        log.debug("批量添加/修改");
        serveRateDao.save(serveRates);
        return JsonResp.ok();
    }

    /**
     * @获取详情-ByServeRateId
     * @param serveRateId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/serveRateDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findServeRateDetailsByServeRateId(Long serveRateId) {
        log.debug("获取详情-ByServeRateId");
        return JsonResp.ok(serveRateDao.findOne(serveRateId));
    }

    /**
     * @获取详情-ByAreaCode
     * @param areaCode
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/serveRateDetailsByAreaCode",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp serveRateDetailsByAreaCode(String areaCode) {
        log.debug("获取详情-ByAreaCode");

        return JsonResp.ok(serveRateDao.findByAreaCode(areaCode));
    }


    /**
     * @分页查询(jpa方式)
     * @param serveRate 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageServeRateJpa(@RequestBody(required = false) ServeRate serveRate, Integer pageNum, Integer pageSize) {
        log.debug("分页查询(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == serveRate) {
            page = serveRateDao.findAll(pageable); //无条件分页
        }/*else{
            final String condition =  serveRate.getUserName();
            page = serveRateDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        if (StringUtils.isNotBlank(condition)) {
                            expressions.add(cb.like(root.<String>get("condition"), "%"+ condition +"%"));
                        }
                        return predicate;
                    }, pageable);
        }*/
//        List<ServeRate> content = page.getContent();
//        for (ServeRate serveRate1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @删除-one(永久)
     * @param serveRateId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteServeRateOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteServeRateOne(Long serveRateId) {
        log.debug("删除-one(永久)");
        serveRateDao.delete(serveRateId);
        return JsonResp.ok();
    }

    /**
     * @批量删除(永久)
     * @param serveRates
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeServeRate",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeServeRate(@RequestBody List<ServeRate> serveRates) {
        log.debug("批量删除(永久)");
        serveRateDao.delete(serveRates);
        return JsonResp.ok();
    }

    /**
     * @查看保存的区域内是否已存在服务费率
     * @param serveRate
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/checkRateDetail",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp checkRateDetail(@RequestBody ServeRate serveRate){
        log.debug("查看保存的区域内是否已存在服务费率");
        ServeRate serveRateOld=serveRateDao.findByAreaCode(serveRate.getAreaCode());
        if(serveRateOld!=null){
            return JsonResp.fa("该区域已存在服务费率,是否确定更换原有地址？");
        }
        return  JsonResp.ok();
    }


    /**
     * @保存服务费率
     * @param serveRate
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/saveRates",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp saveRates(@RequestBody ServeRate serveRate){
        log.debug("保存服务费率");
        serveRate.setStatus(0);
        serveRateDao.save(serveRate);
        return JsonResp.ok();
    }

    /**
     * @更新服务费率
     * @param serveRate
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/updateRateDetail",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp updateRateDetail(@RequestBody  ServeRate serveRate){
        log.debug("更新服务费率");
        ServeRate serveRateOld=serveRateDao.findByAreaCode(serveRate.getAreaCode());
        serveRateOld.setFulltimeRate(serveRate.getFulltimeRate());
        serveRateDao.save(serveRateOld);
        return  JsonResp.ok();
    }

    /**
     * @获取详情-ByUserId
     * @param userId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/serveRateByUserId",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp serveRateByUserId(Long userId) {
        log.debug("获取详情-ByUserId");
        User user = userDao.findOne(userId);
        Address address = addressDao.findOne(user.getAddress());
        return JsonResp.ok(serveRateDao.findByAreaCode(address.getAreaCode()));
    }

}
